<template>
  <!-- 修改密码 -->
  <el-form v-if="formType==4" class="f-form" ref="formRef" label-width="120px" :model="formData" :rules="formRules">
    <el-form-item label="新密码" prop="password">
      <el-input v-model="formData.password" type="password" placeholder="请输入新密码" />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirm_password">
      <el-input v-model="formData.confirm_password" type="password" placeholder="请输入确认密码" />
    </el-form-item>
  </el-form>
  <!-- 充值 -->
  <el-form v-if="formType==1" class="f-form" ref="formRef" label-width="120px" :model="formData" :rules="formRules">
    <el-form-item label="金额" prop="money">
      <el-input v-model="formData.money" placeholder="请输入充值金额, 扣除请输入负数" />
    </el-form-item>
    <el-form-item label="备注">
      <el-input v-model="formData.remark" placeholder="请输入备注" disabled />
    </el-form-item>
    <el-form-item label="操作密码" prop="password">
      <el-input v-model="formData.password" type="password" show-password placeholder="请输入操作密码" />
    </el-form-item>
  </el-form>
  <!-- 用户转移 -->
  <el-form v-if="formType==2" class="f-form" ref="formRef" label-width="120px" :model="formData" :rules="formRules">
    <el-form-item label="转出门店">
      <el-input :value="detail?.store_info.title" disabled/>
    </el-form-item>
    <el-form-item label="转入门店" prop="to_store_id">
      <el-select v-model="formData.to_store_id" filterable class="min-w-[400px]" placeholder="请选择转入门店">
        <el-option v-for="item in detail?.sub_info" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="提示">
      <span class="text-[red]">将有 {{detail?.count_user}} 名用户转入新门店，请仔细核对</span>
    </el-form-item>
  </el-form>
  <!-- 资产转移 -->
  <el-form v-if="formType==3" class="f-form" ref="formRef" label-width="120px" :model="formData" :rules="formRules">

    <el-form-item label="转出门店">
      <el-input :value="detail?.store_info.title" disabled class="max-w-[360px]"/>
    </el-form-item>
    <el-form-item label="门店余额">
      <el-input :value="detail?.store_info.money" disabled class="max-w-[360px]">
        <template #suffix>元</template>
      </el-input>
    </el-form-item>
    <el-form-item label="转入门店" prop="to_store_id">
      <el-select v-model="formData.to_store_id" filterable class="min-w-[360px]" placeholder="请选择转入门店">
        <el-option v-for="item in detail?.sub_info" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="转出金额" prop="money">
      <el-input v-model="formData.money" placeholder="请输入转出金额" class="max-w-[360px]">
        <template #suffix>元</template>
      </el-input>
      <el-button type="primary" text @click="handleAll">全部</el-button>
    </el-form-item>
    <el-form-item label="确认金额" prop="conformMoney">
      <el-input v-model="formData.conformMoney" placeholder="请输入确认金额" class="max-w-[360px]">
        <template #suffix>元</template>
      </el-input>
    </el-form-item>
    <el-form-item label="提示">
      <span class="text-[red]">将自己的余额转给下级或者下级的下级门店，请仔细核对!</span>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { getChangeStoreInfoApi, rechargeApi, transferMoneyApi, transferUserApi, updatePasswordApi } from '@/addon/htscrm/api'
import { t } from '@/lang'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { ref, reactive } from 'vue'

const defaultFormData = {
    // 充值金额
    money: '',
    // 备注
    remark: '后台手动充值',
    // 充值密码
    password: '',
    // ---- 转移
    // 转出门店
    store_id: 0,
    // 转入门店
    to_store_id: 0,
    conformMoney: '',

    // --修改密码
    confirm_password: ''
}
type IFormData = Partial<typeof defaultFormData>
/** 表单实例 */
const formRef = ref<FormInstance>()
/** 表单数据 */
const formData = ref<IFormData>({ ...defaultFormData })
// 表单规则
const formRules = reactive<FormRules>({
    money: [
        { required: true, message: '请输入金额' },
        // 最多两位小数的数字,
        { pattern: /^-?[0-9]+(.[0-9]{1,2})?$/, message: '请输入正确的金额' }
    ],
    conformMoney: [
        { required: true, message: '请输入确认金额' },
        { pattern: /^[0-9]+(.[0-9]{1,2})?$/, message: '请输入正确的金额' },
        {
            validator: (rule: any, value: any, callback: any) => {
                if (value !== formData.value.money) callback(new Error('确认金额与金额不一致'))
                else callback()
            }
        }
    ],
    to_store_id: [
        { required: true, message: '请选择转出门店' }
    ],
    password: [
        { required: true, message: '请输入密码' }
    ],
    confirm_password: [
        { required: true, message: '请输入确认密码' }
    ]
})

const formType = ref(0)

const detail = ref<IChangeStoreInfo>()

/**
 * @description 初始化
 */
function init (row: IUserItem, type: number) {
    console.log(type)

    formRef.value?.resetFields()
    formType.value = type
    formData.value.store_id = row.id
    formData.value.to_store_id = 0

    getChangeStoreInfo(row.id!)
}

/**
 * @description 提交保存
 */
function submit () {
    return new Promise((resolve, reject) => {
        formRef.value?.validate(async (valid) => {
            if (valid) {
                let res: any
                switch (Number(formType.value)) {
                    case 1:
                        // 充值
                        res = await rechargeApi({
                            store_id: formData.value.store_id!,
                            money: Number(formData.value.money)!,
                            password: formData.value.password!,
                            remark: formData.value.remark!
                        })
                        ElMessage.success(res?.msg)
                        break
                    case 2:
                        if (detail.value?.count_user === 0) {
                            ElMessage.error('该门店暂无用户')
                            return
                        }
                        // 用户转移
                        res = await transferUserApi({
                            store_id: formData.value.store_id!,
                            to_store_id: formData.value.to_store_id!
                        })
                        ElMessage.success(res?.msg)
                        break
                    case 3:
                        // 资产转移
                        res = await transferMoneyApi({
                            store_id: formData.value.store_id!,
                            to_store_id: formData.value.to_store_id!,
                            money: Number(formData.value.money)
                        })
                        ElMessage.success(res?.msg)
                        break
                    case 4:
                        if (formData.value.password !== formData.value.confirm_password) {
                            ElMessage.error('密码不一致，请重新输入')
                            return
                        }
                        // 修改密码
                        res = await updatePasswordApi({
                            store_id: formData.value.store_id!,
                            password: formData.value.password!
                        })
                        ElMessage.success('修改成功')
                        break
                }

                resolve(true)
            } else {
                reject(new Error(t('form.validateError')))
            }
        })
    })
}

/**
 * @description 获取门店列表
 */
async function getChangeStoreInfo (id:number) {
    const res = await getChangeStoreInfoApi(id)
    detail.value = {
      ...res.data,
      sub_info: [
        {
          id: 0,
          name: '平台'
        },
        ...res.data?.sub_info || []
      ]
    };
}

function handleAll () {
    formData.value.money = detail.value?.store_info.money
    formData.value.conformMoney = detail.value?.store_info.money
}

defineExpose({
    init,
    submit
})
</script>
<style lang="scss" scoped>
</style>
